package com.wgchao.authodemo.domian.event.base.impl;

import com.wgchao.authodemo.domian.entity.base.AgencyDO;
import com.wgchao.authodemo.domian.entity.base.dao.AgencyDao;
import com.wgchao.authodemo.domian.event.base.AgencyEvent;
import com.wgchao.authodemo.infrastructure.exception.ParamNotLegalexception;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName: AgencyEvent
 * @author: wgchao
 * @createTime: 2019/12/10 4:09 PM
 * @Description: 机构服务
 */
@Service
public class AgencyEventImpl implements AgencyEvent {
    @Autowired
    private AgencyDao agencyDao;

    /**
     * 保存机构信息
     * @param agencyDO
     * @return
     */
    @Override
    public AgencyDO save(AgencyDO agencyDO) {
        //TODO 检查创建人是否合法
        if(!isLegal(agencyDO.getParAgencyCode())){
            throw new ParamNotLegalexception("父机构不合法");
        }
        agencyDO.setAgencyDao(agencyDao);
        agencyDO.createExpand();
        agencyDO = agencyDao.saveOrUpdate(agencyDO);
        return agencyDO;
    }

    @Override
    public AgencyDO search(String code) {
        return agencyDao.search(code);
    }

    /**
     * 机构合法性检查
     * @param code 机构编号
     * @return
     */
    private boolean isLegal(String code){
        AgencyDO agencyDO = agencyDao.search(code);
        if(agencyDO == null){
            return false;
        }
        if(agencyDO.isDeleteFlag()){
            return false;
        }
        return true;
    }
}
